<style>
    * {
        box-sizing: border-box;
    }

    html, body {
        margin: 0;
        padding: 0;
        height: 100%;
        overflow: hidden;
    }

    /* 主容器 */
    .bt-form {
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        height: 100% !important;
        min-height: 100% !important;
        width: 100% !important;
        overflow: hidden !important;
        position: relative !important;
    }

    .bt-w-main {
        display: flex !important;
        height: 100% !important;
        min-height: 100% !important;
        width: 100% !important;
        background: #f5f7fa !important;
        overflow: hidden !important;
        position: relative !important;
    }

    /* 侧边栏菜单 */
    .bt-form .bt-w-main .bt-w-menu {
        width: 200px !important;
        min-width: 200px !important;
        max-width: 200px !important;
        min-height: 100% !important;
        height: 100% !important;
        max-height: 100% !important;
        background: linear-gradient(180deg, #667eea 0%, #764ba2 100%) !important;
        padding: 0 !important;
        margin: 0 !important;
        box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1) !important;
        flex-shrink: 0 !important;
        overflow-y: auto !important;
        overflow-x: hidden !important;
        display: flex !important;
        flex-direction: column !important;
        align-self: stretch !important;
    }
    
    .menu-items {
        flex: 1;
        padding: 25px 0;
    }

    .bt-w-menu p {
        padding: 16px 20px 16px 18px;
        color: rgba(255, 255, 255, 0.8);
        cursor: pointer;
        transition: all 0.3s ease;
        font-size: 15px;
        font-weight: 500;
        border-left: 4px solid transparent;
        margin: 8px 0;
        white-space: nowrap;
        line-height: 1.6;
        letter-spacing: 0.5px;
        text-align: left;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    /* 版本号区域 */
    .menu-version {
        padding: 20px;
        border-top: 1px solid rgba(255, 255, 255, 0.2);
        background: rgba(0, 0, 0, 0.1);
        text-align: center;
        color: rgba(255, 255, 255, 0.7);
        font-size: 12px;
        line-height: 1.5;
    }
    
    .menu-version .version-label {
        display: block;
        font-size: 11px;
        color: rgba(255, 255, 255, 0.5);
        margin-bottom: 5px;
        text-transform: uppercase;
        letter-spacing: 1px;
    }
    
    .menu-version .version-number {
        display: block;
        font-size: 18px;
        font-weight: 700;
        color: #fff;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }
    
    .menu-version .author-info {
        display: block;
        margin-top: 8px;
        font-size: 11px;
        color: rgba(255, 255, 255, 0.6);
    }

    .bt-w-menu p:hover {
        background: rgba(255, 255, 255, 0.1);
        color: #fff;
    }

    .bt-w-menu p.bgw {
        background: rgba(255, 255, 255, 0.2);
        color: #fff;
        border-left-color: #fff;
        box-shadow: inset 0 0 10px rgba(255, 255, 255, 0.1);
    }

    /* 侧边栏滚动条美化 */
    .bt-w-menu::-webkit-scrollbar {
        width: 6px;
    }

    .bt-w-menu::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 3px;
    }

    .bt-w-menu::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.3);
        border-radius: 3px;
    }

    .bt-w-menu::-webkit-scrollbar-thumb:hover {
        background: rgba(255, 255, 255, 0.5);
    }

    /* 内容区域 */
    .bt-form .bt-w-main .bt-w-con {
        flex: 1 !important;
        padding: 15px !important;
        overflow-y: auto !important;
        overflow-x: hidden !important;
        background: #f5f7fa !important;
        height: 100% !important;
        margin-left: 0 !important;
        margin-right: 0 !important;
        margin-top: 0 !important;
        margin-bottom: 0 !important;
        position: relative !important;
    }

    .bt-w-con .plugin_body,
    .bt-w-con > .plugin_body,
    div.bt-w-con div.plugin_body {
        width: 100% !important;
        max-width: 100% !important;
        min-width: 100% !important;
        background: #fff !important;
        border-radius: 12px !important;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08) !important;
        padding: 25px !important;
        min-height: calc(100% - 30px) !important;
        height: auto !important;
        margin: 0 auto 0 0 !important;
        box-sizing: border-box !important;
    }

    .box_conter {
        display: none;
        animation: fadeIn 0.3s ease;
        width: 100% !important;
        max-width: 100% !important;
        box-sizing: border-box !important;
    }

    .box_conter.active {
        display: block;
        width: 100% !important;
        max-width: 100% !important;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* 状态页面 */
    .status-container {
        max-width: 800px;
        margin: 0 auto;
    }

    .status-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 12px;
        padding: 30px;
        color: #fff;
        margin-bottom: 30px;
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
    }

    .status-card .status {
        font-size: 18px;
        margin-bottom: 20px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .status-icon {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        display: inline-block;
        animation: pulse 2s infinite;
    }

    .status-icon.running {
        background: #52c41a;
        box-shadow: 0 0 10px #52c41a;
    }

    .status-icon.stopped {
        background: #ff4d4f;
        box-shadow: 0 0 10px #ff4d4f;
    }

    @keyframes pulse {
        0%, 100% {
            opacity: 1;
        }
        50% {
            opacity: 0.5;
        }
    }

    .status-actions {
        display: flex;
        gap: 15px;
        flex-wrap: wrap;
    }

    .status-btn {
        padding: 10px 25px;
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        border-radius: 6px;
        color: #fff;
        cursor: pointer;
        transition: all 0.3s ease;
        font-size: 14px;
        font-weight: 500;
    }

    .status-btn:hover {
        background: rgba(255, 255, 255, 0.3);
        transform: translateY(-2px);
    }

    .info-box {
        background: #fff;
        border-radius: 12px;
        padding: 30px;
        border: 2px solid #e8e8e8;
    }

    .info-box h3 {
        color: #333;
        margin-bottom: 15px;
        font-size: 18px;
        font-weight: 600;
        padding-bottom: 10px;
        border-bottom: 2px solid #f0f0f0;
    }

    .info-box h3:first-child::before {
        content: "📋";
        font-size: 20px;
        margin-right: 8px;
    }

    .info-box p {
        color: #666;
        line-height: 1.8;
        font-size: 14px;
    }
    
    .info-box p strong {
        color: #333;
    }
    
    /* 使用流程高亮区域 */
    .usage-steps {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        padding: 20px;
        border-radius: 8px;
        border-left: 4px solid #667eea;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    }
    
    .usage-steps p {
        margin: 0;
        line-height: 2.2;
    }
    
    .usage-steps strong {
        color: #667eea;
        font-weight: 600;
    }
    
    /* 场景卡片 */
    .scenario-item {
        margin: 8px 0;
        padding: 8px 0;
    }
    
    .scenario-item strong {
        color: #333;
        font-weight: 600;
    }
    
    /* 注意事项 */
    .notice-box {
        background: #fff5f5;
        padding: 15px 20px;
        border-radius: 8px;
        border-left: 4px solid #ff4d4f;
    }
    
    .notice-box p {
        color: #d32f2f;
        line-height: 2;
        margin: 0;
    }
    
    .notice-box strong {
        font-weight: 700;
    }

    /* 配置列表 */
    .config-header {
        margin-bottom: 20px;
    }

    .add-config-btn {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #fff;
        border: none;
        padding: 12px 30px;
        border-radius: 6px;
        cursor: pointer;
        font-size: 14px;
        font-weight: 500;
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
    }

    .add-config-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }

    .config-list-table {
        margin-top: 20px;
        overflow-x: auto;
    }

    .config-list-table table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
    }

    .config-list-table th {
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        padding: 15px;
        text-align: center;
        color: #333;
        font-weight: 600;
        font-size: 14px;
        border-bottom: 2px solid #667eea;
    }

    .config-list-table th:first-child {
        border-top-left-radius: 8px;
    }

    .config-list-table th:last-child {
        border-top-right-radius: 8px;
    }

    .config-list-table td {
        padding: 15px;
        text-align: center;
        border-bottom: 1px solid #f0f0f0;
        color: #555;
        font-size: 13px;
    }

    .config-list-table tbody tr {
        transition: all 0.2s ease;
    }

    .config-list-table tbody tr:hover {
        background: #f8f9fa;
        transform: scale(1.01);
    }

    .config-list-table tbody tr:last-child td {
        border-bottom: none;
    }

    .bt-link {
        color: #667eea;
        cursor: pointer;
        text-decoration: none;
        transition: all 0.2s ease;
        font-weight: 500;
    }

    .bt-link:hover {
        color: #764ba2;
        text-decoration: underline;
    }

    .el-divider {
        display: inline-block;
        width: 1px;
        height: 14px;
        background: #ddd;
        margin: 0 10px;
        vertical-align: middle;
    }

    /* 日志页面 */
    .log-header {
        margin-bottom: 20px;
    }

    .clear-log-btn {
        background: #ff4d4f;
        color: #fff;
        border: none;
        padding: 10px 25px;
        border-radius: 6px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s ease;
    }

    .clear-log-btn:hover {
        background: #ff7875;
        transform: translateY(-2px);
    }

    .log-container {
        background: #1e1e1e;
        border-radius: 8px;
        padding: 20px;
        height: 550px;
        overflow-y: auto;
        box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.2);
    }

    .log-container::-webkit-scrollbar {
        width: 8px;
    }

    .log-container::-webkit-scrollbar-track {
        background: #2a2a2a;
        border-radius: 4px;
    }

    .log-container::-webkit-scrollbar-thumb {
        background: #555;
        border-radius: 4px;
    }

    .log-container::-webkit-scrollbar-thumb:hover {
        background: #777;
    }

    .log-content {
        color: #ececec;
        font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
        font-size: 13px;
        line-height: 1.6;
        white-space: pre-wrap;
        word-wrap: break-word;
    }

    .log-empty {
        color: #888;
        text-align: center;
        padding: 50px;
        font-size: 14px;
    }

    /* 响应式 */
    @media (max-width: 768px) {
        .bt-form .bt-w-main .bt-w-menu {
            width: 170px !important;
            min-width: 170px !important;
            max-width: 170px !important;
            min-height: 100% !important;
            height: 100% !important;
        }

        .menu-items {
            padding: 20px 0;
        }

        .bt-w-menu p {
            padding: 14px 16px;
            font-size: 14px;
            letter-spacing: 0.3px;
        }

        .menu-version {
            padding: 15px;
        }

        .menu-version .version-number {
            font-size: 16px;
        }

        .bt-w-con {
            padding: 15px !important;
            height: 100%;
        }

        .plugin_body {
            padding: 20px !important;
            min-height: calc(100% - 30px) !important;
        }
    }

    /* 内容区域滚动条美化 */
    .bt-w-con::-webkit-scrollbar {
        width: 8px;
    }

    .bt-w-con::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 4px;
    }

    .bt-w-con::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 4px;
    }

    .bt-w-con::-webkit-scrollbar-thumb:hover {
        background: #555;
    }
</style>
<div class="bt-form">
    <div class="bt-w-main">
        <!--侧边栏菜单-->
        <div class="bt-w-menu">
            <div class="menu-items">
                <p class="bgw">📊 状态</p>
                <p>⚙️ 同步设置</p>
                <p>📝 日志</p>
                <p>❌ 错误日志</p>
            </div>
            <div class="menu-version">
                <span class="version-label">Version</span>
                <span class="version-number">2.0.2</span>
                <span class="author-info">by <a href="https://www.jiulingyun.cn/" target="_blank">九灵云</a></span>
            </div>
        </div>
        
        <!--主内容区域-->
        <div class="bt-w-con">
            <div class="plugin_body">
                <!-- 状态页面 -->
                <div class="box_conter status_page active">
                    <div class="status-container">
                        <div class="status-card">
                            <div class="status">
                                <span>当前状态：</span>
                                <span class="status-text">开启</span>
                                <span class="status-icon running"></span>
                            </div>
                            <div class="status-actions">
                                <button class="status-btn lsyncd_start" style="display:none;"
                                        onclick="remoteback.set_job_status({type:'start',title:'启动'})">
                                    🚀 启动服务
                                </button>
                                <button class="status-btn lsyncd_stop" style="display:none;"
                                        onclick="remoteback.set_job_status({type:'stop',title:'停止'})">
                                    ⏸️ 停止服务
                                </button>
                                <button class="status-btn"
                                        onclick="remoteback.set_job_status({type:'run',title:'运行'})">
                                    ▶️ 直接运行
                                </button>
                            </div>
                        </div>
                        
                        <div class="info-box">
                            <h3>功能特性</h3>
                            <p style="margin-bottom: 25px;">
                                <strong style="color: #667eea;">🎯 核心功能：</strong>将当前服务器的网站、数据库、FTP、计划任务等数据自动同步到异地备份服务器，实现数据容灾备份。<br><br>
                                <strong style="color: #667eea;">✨ 智能环境适配：</strong>自动检测目标服务器环境，缺失的软件（Nginx/Apache/PHP/MySQL等）会自动安装配置，无需手动干预。<br><br>
                                <strong style="color: #667eea;">⏰ 定时自动备份：</strong>支持按分钟或小时设置同步周期，自动定时执行，确保数据实时同步。
                            </p>
                            
                            <h3 style="margin-top: 30px;">使用流程</h3>
                            <div class="usage-steps">
                                <p>
                                    <strong>第一步：</strong>在目标备份服务器开启 <strong>API接口</strong>（设置 → API接口），将本服务器IP加入白名单<br>
                                    <strong>第二步：</strong>点击"同步设置"→"添加配置"，填写目标服务器的面板地址和API密钥<br>
                                    <strong>第三步：</strong>选择要同步的数据（网站、数据库、FTP、计划任务），至少选择一项<br>
                                    <strong>第四步：</strong>设置同步周期（建议2小时以上），点击确定保存<br>
                                    <strong>第五步：</strong>点击"启动服务"开启自动同步，或点击"直接运行"立即执行一次同步
                                </p>
                            </div>
                            
                            <h3 style="margin-top: 30px;">使用场景</h3>
                            <div style="margin-top: 12px;">
                                <div class="scenario-item">💼 <strong>多服务器备份：</strong>将多台生产服务器数据统一同步到一台备份服务器</div>
                                <div class="scenario-item">🔄 <strong>服务器迁移：</strong>快速将整个服务器环境迁移到新服务器</div>
                                <div class="scenario-item">🛡️ <strong>数据容灾：</strong>定时异地备份，防止单点故障导致数据丢失</div>
                                <div class="scenario-item">📦 <strong>环境复制：</strong>快速复制生产环境到测试/开发服务器</div>
                            </div>
                            
                            <h3 style="margin-top: 30px;">注意事项</h3>
                            <div class="notice-box">
                                <p>
                                    ⚠️ 目前仅支持 <strong>Linux系统</strong>（CentOS/Ubuntu/Debian等）<br>
                                    ⚠️ 目标服务器宝塔版本需 <strong>6.9.8</strong> 及以上<br>
                                    ⚠️ 建议在<strong>低峰期</strong>执行同步，避免影响业务<br>
                                    ⚠️ 首次同步时间较长，请耐心等待，可在"日志"中查看进度
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 配置列表页面 -->
                <div class="box_conter config_page">
                    <div class="config-header">
                        <button type="button" id="add-config-btn" class="add-config-btn">
                            ➕ 添加配置
                        </button>
                    </div>
                    <div class="config-list-table">
                        <table>
                            <thead>
                                <tr>
                                    <th>服务器名称</th>
                                    <th>同步周期</th>
                                    <th>最近同步时间</th>
                                    <th>下一次同步时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="config-list">
                                <!-- 动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <!-- 日志页面 -->
                <div class="box_conter log_page">
                    <div class="log-header">
                        <button type="button" class="clear-log-btn" onclick="remoteback.clear_logs('logs')">
                            🗑️ 清空日志
                        </button>
                    </div>
                    <div class="log-container">
                        <div id="logs-view" class="log-content">暂无日志</div>
                    </div>
                </div>
                
                <!-- 错误日志页面 -->
                <div class="box_conter error_log_page">
                    <div class="log-header">
                        <button type="button" class="clear-log-btn" onclick="remoteback.clear_logs('error')">
                            🗑️ 清空错误日志
                        </button>
                    </div>
                    <div class="log-container">
                        <div id="error-logs-view" class="log-content">暂无日志</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" src="/remoteback/static/js/layui.js"></script>
<script id="config_list_tpl" type="text/html">
    {{#  layui.each(d, function(index, item){ }}
    {{#
    var fn = function(){
    return item.time_type == 'minute' ? '分钟' : '小时';
    };
    }}
    <tr>
        <td>{{ item.title }}</td>
        <td>
            {{ item.hour }}{{ fn() }}
        </td>
        <td>{{ item.last_sync_time || '-' }}</td>
        <td>{{ item.next_sync_time || '-' }}</td>
        <td>
            <div class="cell">
                <div>
                    <span title="设置" class="bt-link"
                          onclick="remoteback.create_edit_conf_page({config_name:'{{ item.config_name }}'})">设置</span>
                    <div class="el-divider el-divider--vertical" role="separator"
                         style="--el-border-style: solid;"></div>
                    <span title="删除" onclick="remoteback.del_config({config_name:'{{ item.config_name }}'})"
                          class="bt-link">删除</span>
                </div>
            </div>
        </td>
    </tr>
    {{#  }); }}
</script>
<!--JS脚本部分，不要将JS脚本写在其它地方-->
<script type="text/javascript">


    /**
     * 插件交互对象
     * 您的所有JS代码可以写在里面
     * 若不习惯JS的面向对象编程，可删除此对象，使用传统函数化的方式编写
     * */
    var remoteback = {
        plugin_name: 'remoteback',
        plugin_config: {},
        edit_codeMirror: '',
        plugin_layer_index: 0,
        init: function () {
            try {
                var _this = this;
                //定义窗口尺寸
                $('.layui-layer-page').css({'width': '1200px', 'height': '750px'});
                
                // 强制设置布局样式的函数
                function forceLayoutStyles() {
                    // 获取窗口实际高度
                    var layerPage = $('.layui-layer-page');
                    var windowHeight = layerPage.innerHeight() || layerPage.height() || 750;
                    
                    console.log('🔧 应用布局样式，窗口高度:', windowHeight + 'px');
                    
                    // 使用内联样式强制设置高度
                    $('.bt-form')[0].style.cssText += 'height: ' + windowHeight + 'px !important; min-height: ' + windowHeight + 'px !important;';
                    $('.bt-w-main')[0].style.cssText += 'height: ' + windowHeight + 'px !important; min-height: ' + windowHeight + 'px !important;';
                    
                    // 强制设置左侧菜单高度 - 使用内联样式
                    var menu = $('.bt-w-menu')[0];
                    if (menu) {
                        menu.style.cssText += 'height: ' + windowHeight + 'px !important; min-height: ' + windowHeight + 'px !important; max-height: ' + windowHeight + 'px !important;';
                    }
                    
                    // 移除宝塔默认的 margin-left
                    var con = $('.bt-w-con')[0];
                    if (con) {
                        con.style.cssText += 'margin-left: 0 !important; margin-right: 0 !important; margin-top: 0 !important; margin-bottom: 0 !important; height: ' + windowHeight + 'px !important;';
                    }
                    
                    // 确保 plugin_body 占满宽度
                    $('.plugin_body').attr('style', function(i, style) {
                        return (style || '') + 'width: 100% !important; max-width: 100% !important; min-width: 100% !important; margin: 0 !important; box-sizing: border-box !important;';
                    });
                }
                
                // 初始化时应用
                forceLayoutStyles();
                
                // 延迟再次应用，确保覆盖其他样式
                setTimeout(forceLayoutStyles, 100);
                setTimeout(forceLayoutStyles, 300);
                setTimeout(forceLayoutStyles, 500);
                setTimeout(forceLayoutStyles, 1000);
                
                // 持续监控宽度，前5秒每200ms检查一次
                var checkCount = 0;
                var widthChecker = setInterval(function() {
                    forceLayoutStyles();
                    checkCount++;
                    if (checkCount >= 25) {  // 5秒后停止持续检查
                        clearInterval(widthChecker);
                        console.log('✅ 布局修正完成');
                    }
                }, 200);
                
                // 窗口尺寸变化时重新应用
                $(window).on('resize', function() {
                    forceLayoutStyles();
                });

                $(".menu-items p").click(function () {
                    var index = $(this).index();
                    switch (index) {
                        case 0:
                            _this.get_cron_job();
                            break;
                        case 1:
                            _this.create_conf();
                            break;
                        case 2:
                            _this.get_logs();
                            break;
                        case 3:
                            _this.get_error_logs();
                            break;
                    }

                    $(this).addClass('bgw').siblings().removeClass('bgw');
                    $('.plugin_body .box_conter').eq(index).addClass('active').siblings().removeClass('active');
                    
                    // 每次切换标签页时重新应用布局样式
                    setTimeout(forceLayoutStyles, 10);
                });

                $('#add-config-btn').click(function () {
                    $.get('/remoteback/add_config_page.html', {}, function (rdata) {
                        let addLayer = layer.open({
                            type: 1,
                            title: '添加配置',
                            area: ['1000px', '680px'],
                            btn: ['确定', '取消'],
                            content: rdata,
                            zIndex: 99999999,
                            maxmin: true,
                            yes: function (index, layero) {
                                var formData = {
                                    'time_type': layero.find('#time-type').val(),
                                };
                                layero.find('input').each(function () {
                                    formData[this.name] = this.value;
                                    // 其中checkbox是数组类型
                                    if (this.type === 'checkbox') {
                                        let temp = [];
                                        formData[this.name] = layero.find('input[name="' + this.name + '"]:checked').map(function () {
                                            temp.push({
                                                name: this.value,
                                                id: $(this).data('id'),
                                                error: '',
                                                state: 0
                                            })
                                        }).get()
                                        // 对象字符出化
                                        temp = JSON.stringify(temp)
                                        formData[this.name] = temp
                                    }
                                });
                                if (!formData.panel || !formData.token || !formData.hour || !formData.title || !formData.time_type) {
                                    layer.msg('请填写完整', {icon: 2})
                                    return
                                }
                                request_plugin(remoteback.plugin_name, 'add_config', formData, function (rdata) {
                                    console.log('添加配置返回结果:', rdata);
                                    
                                    if (!rdata) {
                                        layer.msg('服务器无响应，请稍后重试', {icon: 2, time: 3000});
                                        return;
                                    }
                                    
                                    if (rdata.status) {
                                        layer.msg('添加成功', {icon: 1});
                                        layer.close(addLayer);
                                        remoteback.create_conf();
                                    } else {
                                        var errorMsg = rdata.msg || rdata.error_msg || '添加失败，请查看错误日志';
                                        layer.msg(errorMsg, {icon: 2, time: 5000, shift: 6});
                                        console.error('添加配置失败:', rdata);
                                    }
                                })
                            }
                        })
                    })

                })

                _this.get_cron_job();

                // 获取本窗口在全局中的层索引index
                _this.plugin_layer_index = layer.getFrameIndex(window.name);
                console.log('当前插件窗口层级：', _this.plugin_layer_index)
            } catch (e) {
                console.error('插件初始化失败:', e);
            }

        },
        //构造首页状态内容
        get_cron_job: function () {
            request_plugin(this.plugin_name, 'get_cron_job', {}, function (rdata) {
                if (!rdata) return;
                try {
                    const isRunning = rdata.status;
                    const statusText = isRunning ? '开启' : '关闭';
                    const iconClass = isRunning ? 'running' : 'stopped';
                    
                    $('.status_page .status-text').text(statusText);
                    $('.status_page .status-icon')
                        .removeClass('running stopped')
                        .addClass(iconClass);
                    
                    $('.status_page .lsyncd_start').toggle(!isRunning);
                    $('.status_page .lsyncd_stop').toggle(isRunning);
                } catch (e) {
                    console.error('获取定时任务状态失败:', e);
                }
            })
        },

        set_job_status: function (args) {
            request_plugin(this.plugin_name, 'set_job_status', args, function (rdata) {
                if (rdata.status) {
                    layer.msg('操作成功！', {icon: 1});
                    remoteback.get_cron_job();
                } else {
                    layer.msg('操作失败，失败原因：' + rdata.msg, {icon: 2});
                    remoteback.get_cron_job();
                }
            });
        },
        add_config: function (args) {
            request_plugin(this.plugin_name, 'add_config', args, function (rdata) {
                if (rdata.status) {
                    this.create_conf();
                    layer.msg('操作成功！', {icon: 1});
                    return true;
                } else {
                    layer.msg('操作失败，失败原因：' + rdata.msg, {icon: 2});
                    return false;
                }
            });
        },
        create_conf: function () {
            request_plugin(this.plugin_name, 'get_sync_config_list', {}, function (rdata) {
                if (!rdata) return;
                try {
                    var configListTpl = config_list_tpl.innerHTML
                    var configListView = $('#config-list')
                    if (rdata.status) {
                        layui.use('laytpl', function () {
                            var laytpl = layui.laytpl;
                            laytpl(configListTpl).render(rdata.data, function (html) {
                                configListView.html(html);
                            });
                        })
                    }
                } catch (e) {
                    console.error('获取配置列表失败:', e);
                }
            })
        },
        create_edit_conf_page: function (args) {
            $.get('/remoteback/edit_config_page.html', args, function (rdata) {
                if (rdata) {
                    let editLayer = layer.open({
                        type: 1,
                        title: '编辑配置',
                        area: ['1000px', '680px'],
                        btn: ['确定', '取消'],
                        content: rdata,
                        zIndex: 99999999,
                        maxmin: true,
                        yes: function (index, layero) {
                            // 获取所有Input数据成对象
                            var formData = {
                                'time_type': layero.find('#time-type').val(),
                            };
                            layero.find('input').each(function () {
                                formData[this.name] = this.value;
                                if (this.type === 'checkbox') {
                                    let temp = [];
                                    formData[this.name] = layero.find('input[name="' + this.name + '"]:checked').map(function () {
                                        temp.push({
                                            name: this.value,
                                            id: $(this).data('id'),
                                            error: '',
                                            state: 0
                                        })
                                    }).get()
                                    // 对象字符出化
                                    temp = JSON.stringify(temp)
                                    formData[this.name] = temp
                                }
                            });
                            if (!formData.panel || !formData.token || !formData.hour || !formData.title || !formData.time_type) {
                                console.log('form-data', formData)
                                layer.msg('请填写完整', {icon: 2})
                                return
                            }
                            request_plugin(remoteback.plugin_name, 'edit_config', formData, function (rdata) {
                                console.log('编辑配置返回结果:', rdata);
                                
                                if (!rdata) {
                                    layer.msg('服务器无响应，请稍后重试', {icon: 2, time: 3000});
                                    return;
                                }
                                
                                if (rdata.status) {
                                    layer.msg('操作成功！', {icon: 1});
                                    layer.close(editLayer);
                                    remoteback.create_conf();
                                } else {
                                    var errorMsg = rdata.msg || rdata.error_msg || '编辑失败，请查看错误日志';
                                    layer.msg(errorMsg, {icon: 2, time: 5000, shift: 6});
                                    console.error('编辑配置失败:', rdata);
                                }
                            })
                        }
                    })
                }
            });
        },
        del_config: function (args) {
            request_plugin(this.plugin_name, 'del_config', args, function (rdata) {
                if (rdata.status) {
                    layer.msg('操作成功！', {icon: 1});
                    remoteback.create_conf();
                } else {
                    layer.msg('操作失败，失败原因：' + rdata.msg, {icon: 2});
                }
            });
        },
        get_logs: function () {
            request_plugin(this.plugin_name, 'get_logs', {}, function (rdata) {
                if (!rdata) return;
                try {
                    if (rdata.status) {
                        $('#logs-view').html(rdata.data.logs);
                    } else {
                        layer.msg('操作失败，失败原因：' + rdata.msg, {icon: 2});
                    }
                } catch (e) {
                    console.error('获取日志失败:', e);
                }
            });
        },
        get_error_logs: function () {
            request_plugin(this.plugin_name, 'get_logs', {}, function (rdata) {
                if (!rdata) return;
                try {
                    if (rdata.status) {
                        $('#error-logs-view').html(rdata.data.logs_error);
                    } else {
                        layer.msg('操作失败，失败原因：' + rdata.msg, {icon: 2});
                    }
                } catch (e) {
                    console.error('获取错误日志失败:', e);
                }
            });
        },
        clear_logs: function (type = 'all') {
            request_plugin(this.plugin_name, 'clear_logs', {
                type: type
            }, function (rdata) {
                if (rdata.status) {
                    layer.msg('操作成功！', {icon: 1});
                    remoteback.get_logs();
                    remoteback.get_error_logs();
                } else {
                    layer.msg('操作失败，失败原因：' + rdata.msg, {icon: 2});
                }
            });
        }

    }

    /**
     * 发送请求到插件
     * 注意：除非你知道如何自己构造正确访问插件的ajax，否则建议您使用此方法与后端进行通信
     * @param plugin_name    插件名称 如：demo
     * @param function_name  要访问的方法名，如：get_logs
     * @param args           传到插件方法中的参数 请传入数组，示例：{p:1,rows:10,callback:"demo.get_logs"}
     * @param callback       请传入处理函数，响应内容将传入到第一个参数中
     * @param timeout        超时时间，默认10000毫秒
     */
    function request_plugin(plugin_name, function_name, args, callback, timeout) {
        if (!timeout) timeout = 10000;
        var load = layer.load(1, {shade: [0.1, '#fff']});
        
        console.log('📤 发送请求:', function_name, args);
        
        $.ajax({
            type: 'POST',
            url: '/plugin?action=a&s=' + function_name + '&name=' + plugin_name,
            data: args,
            timeout: timeout,
            success: function (rdata) {
                layer.close(load);
                
                console.log('📥 收到响应:', function_name, rdata);
                
                // 检查响应数据
                if (!rdata) {
                    console.error('❌ 响应数据为空');
                    layer.msg('服务器返回数据为空，请稍后重试', {icon: 2, time: 3000});
                    if (callback) callback(null);
                    return;
                }
                
                // 处理响应
                if (!callback) {
                    var msg = rdata.msg || '操作完成';
                    layer.msg(msg, {icon: rdata.status ? 1 : 2, time: 3000});
                    return;
                }
                
                callback(rdata);
            },
            error: function (xhr, type, errorMsg) {
                layer.close(load);
                
                console.error('❌ 请求失败:', {
                    status: xhr.status,
                    type: type,
                    error: errorMsg,
                    response: xhr.responseText
                });
                
                var errMsg = '请求失败！';
                if (xhr.status === 0) {
                    errMsg = '无法连接服务器，请检查网络是否正常';
                } else if (xhr.status === 404) {
                    errMsg = '请求的功能不存在（404）';
                } else if (xhr.status === 500) {
                    errMsg = '服务器内部错误（500），请查看错误日志';
                } else if (type === 'timeout') {
                    errMsg = '请求超时，操作可能较慢，请稍后查看日志确认';
                } else if (xhr.status === 403) {
                    errMsg = '权限不足（403）';
                } else {
                    errMsg = `请求失败（状态码：${xhr.status}）`;
                }
                
                layer.msg(errMsg, {icon: 2, time: 5000, shift: 6});
                
                // 如果有回调，传递错误信息
                if (callback) {
                    callback({status: false, msg: errMsg});
                }
            }
        });
    }

    //第一次打开窗口时调用
    remoteback.init();

</script>